package ar.edu.itba.pod.legajo46470.event;

import static com.google.common.base.Preconditions.checkNotNull;

import java.io.Serializable;
import java.rmi.RemoteException;

import org.apache.log4j.Logger;
import org.joda.time.DateTime;

import ar.edu.itba.event.EventInformation;
import ar.edu.itba.pod.agent.runner.Agent;
import ar.edu.itba.pod.legajo46470.cluster.node.ClusterNode;
import ar.edu.itba.pod.multithread.MultiThreadEventDispatcher;

public class DistributedEventDispatcher extends MultiThreadEventDispatcher {
	private final static Logger LOGGER = Logger.getLogger(DistributedEventDispatcher.class);
	private ClusterNode clusterNode;
	
	public DistributedEventDispatcher(ClusterNode clusterNode) {
		checkNotNull(clusterNode, "Cluster Node cannot be null");
		this.clusterNode = clusterNode;
	}
	
	@Override
	public void publish(Agent source, Serializable event) throws InterruptedException {
		EventInformation eventInfo;
		
		super.publish(source, event);
		eventInfo = new EventInformation(event, clusterNode.getNodeInfo().id(), source);
		eventInfo.setReceivedTime(DateTime.now().getMillis());
		try {
			clusterNode.getRemoteEventDispatcher().publish(eventInfo);
		} catch (RemoteException e) {
			LOGGER.error("Error in local stub, remote exception");
		}
		
	}
	
	public void publishInternal(Agent source, Serializable event) throws InterruptedException {
		super.publish(source, event);
	}
}
